<template>
  <div class="tablePageWarp systemUserListWrap listSearchWrap">
    <!-- 搜索区域 -->
    <div class="table-page-search-wrapper commonSelectWidth systemUserListSearch">
      <a-form>
        <a-row :gutter="[16, 0]">
          <a-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="8"
            :xl="4"
            :xxl="4">
            <!-- 角色 -->
            <a-form-item :colon="false">
              <role-select
                :has-first-option="true"
                :default-value="queryParams.roleIds"
                @changerole="changeRole"
              ></role-select>
            </a-form-item>
          </a-col>
          <!-- 帐号 -->
          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="8"
            :xl="4"
            :xxl="4">
            <a-form-item :colon="false">
              <a-input
                v-model.trim="queryParams.account"
                @keyup.enter="refreshData(true)"
                :placeholder="$t('loginAccount')"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="8"
            :xl="4"
            :xxl="4">
            <a-form-item :colon="false">
              <a-input
                v-model.trim="queryParams.name"
                :placeholder="$t('pleaseInput') + $t('userName').toLowerCase()"
                @keyup.enter="refreshData(true)"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="8"
            :xl="4"
            :xxl="4">
            <a-form-item :colon="false">
              <a-select v-model="queryParams.enabled" allow-clear :placeholder="$t('pleaseSelect') + '用户账号状态'" @change="refreshData(true)">
                <a-select-option v-for="item in accountStatusList" :key="item.value" :value="item.value">
                  {{item.label}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="8"
            :xl="4"
            :xxl="4">
            <a-form-item :colon="false">
              <a-select v-model="queryParams.onlineStatus" allow-clear :placeholder="$t('pleaseSelect') + '用户在线状态'" @change="refreshData(true)">
                <a-select-option v-for="item in onlineStatusList" :key="item.value" :value="item.value">
                  {{item.label}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <div class="searchBtns">
          <a-button-group>
            <auth-button type="primary" :auth="managePerms.user.view" @click="refreshData(true)">
              <i class="iconfont icon-chazhao"></i>
              {{ $t('inquiry') }}
            </auth-button>
            <a-button @click="clearCondition">
              <i class="iconfont icon-qingkong"></i>
              {{ $t('clear') }}
            </a-button>
          </a-button-group>
          <auth-button :auth="managePerms.user.add" @click="handleAdd">
            <i class="iconfont icon-xinjian"></i>
            {{ $t('user') }}
          </auth-button>
        </div>
      </a-form>
    </div>
    <!-- 列表区域 -->
    <div class="withMinHeightTbodyBox systemUserListTb">
      <s-table
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1300 }"
        row-key="id"
        class="h100"
        ref="table"
      >
        <template slot="userName" slot-scope="text, record">
          <div class="userNameTd">
            <svg class="icon" style="color: green; cursor: pointer" aria-hidden="true" @click="toggleUserState(record)">
              <use xlink:href="#icon-zhengchang" v-if="record.enabled == 1"></use>
              <use xlink:href="#icon-notzhengchang" v-else></use>
            </svg>
            <span class="nameText">{{ text }}</span>
            <a-tag v-for="role in record.roles" :key="role.id" :color="roleTagColors[role.id]">
               <table-ellipsis :text="role.name"></table-ellipsis>
              </a-tag>
          </div>
        </template>
        <template slot="org" slot-scope="text">
          <table-ellipsis :text="text"></table-ellipsis>
        </template>
        <template slot="email" slot-scope="text, record">
          <table-ellipsis :text="record.email"></table-ellipsis>
        </template>
        <template slot="account" slot-scope="text, record">
          <table-ellipsis :text="record.account"></table-ellipsis>
        </template>
        <template slot="relatedModel" slot-scope="text, record">
          <a @click="doAction('lookupRelatedModel', record)" v-if="record.modelCount">
            <i class="iconfont icon-chexing"></i>
            <span style="font-weight: bolder; margin-left: 5px"> {{ record.modelCount }}</span>
          </a>
          <div v-else>
            <i class="iconfont icon-chexing"></i>
            <span style="margin-left: 5px">0</span>
          </div>
        </template>
        <template slot="remark" slot-scope="text, record">
          <table-ellipsis :text="record.remark || $t('none')"></table-ellipsis>
        </template>
        <template slot="status" slot-scope="text, record">
          <table-ellipsis :text="$t('normal')" v-if="record.enabled == 1"/>
          <table-ellipsis :text="$t('未授权')" v-else-if="record.enabled == 2"/>
          <table-ellipsis :text="$t('停用')" v-else="record.enabled == 0"/>
        </template>
        <template slot="onlineStatus" slot-scope="text, record">
          <table-ellipsis :text="$t('在线')" v-if="record.onlineStatus == 1"/>
          <div class="offLine" v-else-if="record.onlineStatus == 0">
            <p>离线</p>
            <p class="tip">
              最后离线时间：{{record.beforeDays}}天前</p>
            <p class="tip">
              {{ $commonFun.getDateTimeStr(record.lastLogoutTime) }}
            </p>
          </div>
          
          <!-- <table-ellipsis :text="$t('超时')" v-else-if="record.enabled == 2"/> -->
          <!-- <table-ellipsis :text="$t('离线')" v-else="record.enabled == 0"/> -->
        </template>
        <span slot="action" slot-scope="text, record">
          <template>
            <operation-menu
              :menus="tbRowMenus"
              @clickaction="
                (key) => {
                  doAction(key, record)
                }
              "
            ></operation-menu>
          </template>
        </span>
      </s-table>
    </div>
  </div>
</template>

<script>
// import moment from 'moment'
import { mapState } from 'vuex'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import OperationMenu from '@/components/OperationMenu'
import RoleSelect from '@/views/components/RoleSelect'
import { STable } from '@/components'
import AuthButton from '@/components/AuthButton'
import { managePerms } from '@/config/permission/index'
import { columns } from '../config'
const accountStatusList = [
  {
    label:'正常',
    value:'1'
  },
  {
    label:'未授权',
    value:'2'
  },
  {
    label:'停用',
    value:'0'
  },
]
const onlineStatusList = [
  {
    label:'在线',
    value:'1'
  },
  {
    label:'离线',
    value:'0'
  },
]
export default {
  name: 'ModelList',
  components: {
    tableEllipsis,
    HasNoPermissionTip,
    OperationMenu,
    RoleSelect,
    STable,
    AuthButton
  },
  computed: {
    ...mapState({
      selectedOrg: (state) => state.org.selectedOrg,
      queryParams: (state) => state.user.queryParams,
      userData: (state) => state.user.userData,
      roleTagColors: (state) => state.role.roleTagColors
    }),
    // 用户操作项
    tbRowMenus () {
      const user = this.$t('user')
      return [
        {
          title: this.$t('edit') + user,
          key: 'editUser',
          auth: managePerms.user.edit
        },
        {
          title: this.$t('relatedModel'),
          key: 'relatedModel',
          auth: managePerms.user.relatedModel
        },
        // modify by liang.minglong1
        /*{
          title: this.$t('resetPassword'),
          key: 'resetPwd',
          auth: managePerms.user.resetPwd
        },*/
        {
          title: this.$t('delete') + user,
          key: 'deleteList',
          auth: managePerms.user.delete
        },
        {
          title: this.$t('unlockUser'),
          key: 'relieveLock',
          auth: managePerms.user.unlock
        },
        {
          title: this.$t('yjts'),
          key: 'pushEmail',
          auth: managePerms.user.pushEmail
        }
      ]
    }
  },

  data () {
    return {
      columns,
      managePerms,
      accountStatusList,
      onlineStatusList
    }
  },
  watch: {
    selectedOrg: {
      handler (val) {
        if (!val || !this.$refs.table) {
          return
        }
        if (val.id) {
          this.refreshData(true)
        }
      },
      immediate: true
    }
  },
  created () {},
  methods: {
    loadData (parameter) {
      const organizationIds = this.selectedOrg ? [this.selectedOrg.id] : [];
      return this.$store.dispatch('getUserPageData', { ...this.queryParams, organizationIds, ...parameter })
    },
    changeRole (val) {
      this.queryParams.roleIds = val
    },
    // 批量删除
    deleteList (record) {
      const vm = this
      this.$confirm({
        title: vm.$t('deleteUser'),
        content: vm.$t('deleteUserTip').replace('__CONTENT__', '（' + record.name + '）'),
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.$store.dispatch('deleteUserData', { ids: [record.id] }).then(() => {
            vm.$message.success(vm.$t('successfullyDelete'))
            vm.refreshData() // 刷新页面
          })
        },
        onCancel () {}
      })
    },
    resetPwd (record) {
      const vm = this
      this.$confirm({
        title: vm.$t('resetPassword'),
        content: vm.$t('resetPasswordTip') + '（' + record.name + '）',
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk () {
          vm.$store.dispatch('resetUserPwdData', { id: record.id }).then(() => {
            vm.$message.success(vm.$t('successfullyResetPwd'))
          })
        },
        onCancel () {}
      })
    },
    // 解除冻结
    relieveLock (record) {
      const vm = this
      vm.$api.relieveLock({ ids: [record.id] }).then(() => {
        vm.$message.success(vm.$t('successfullyOperation'))
        vm.refreshData() // 刷新页面
      })
    },
    // 编辑,删除,重置密码,关联车型,查看关联车型
    doAction (key, row) {
      if (this[key]) {
        this[key](row)
        return
      }
      this.$emit('clickbtn', { type: key, data: row })
    },
    // 新建
    handleAdd () {
      this.$emit('clickbtn', { type: 'addUser', data: null })
    },
    clearCondition () {
      this.$store.commit('resetUserQueryParams')
      this.refreshData(true)
    },
    refreshData (isToFirstPage = false) {
      let obj = null
      if (isToFirstPage) {
        obj = { current: 1 }
      }
      if (this.$refs.table && typeof this.$refs.table.loadData === 'function') {
        this.$refs.table.loadData(obj)
      }
    },
    // 停用与启用用户
    toggleUserState (record) {
      const vm = this
      const actionTitle = this.$t(record.enabled==0 ? 'disabled' : 'start')
      this.$confirm({
        title: vm.$t('systemTip'),
        content: vm.$t('enableUserTip').replace('__ACTION__', actionTitle) + '（' + record.name + '）',
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.$store.dispatch('enableUserData', { ids: [record.id], enabled: ((record.enabled==1)?false:true) }).then(() => {
            vm.$message.success(vm.$t('successfullyOperation'))
            vm.refreshData() // 刷新页面
          })
        },
        onCancel () {}
      })
    }
  }
}
</script>
<style scoped lang="less">
.systemUserListWrap {
  display: flex;
  flex-direction: column;
  .systemUserListSearch {
    flex: none;
  }
  .systemUserListTb {
    flex: 1 0 0;
  }
}
.userNameTd {
  width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
  .nameText {
    margin: 0 10px 0 5px;
  }
}
</style>
<style lang="less">
.systemUserListWrap {
  @media (max-width: 1200px) {
    .searchBtns button {
      margin-top: 16px;
    }
  }
}
.overTime{
  .tip{
    font-size: 6px;
  }
}
.offLine{
  .tip{
    font-size: 6px;
  }
}
</style>
